#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    // 设置标题
    this->setWindowTitle("我的记事本");

    // 创建菜单栏
    QMenuBar* menuBar = this->menuBar();
    this->setMenuBar(menuBar);

    // 创建菜单
    QMenu* menuFile = new QMenu("文件");
    menuBar->addMenu(menuFile);

    // 创建菜单项
    QAction* act1 = new QAction("保存");
    QAction* act2 = new QAction("加载");

    menuFile->addAction(act1);
    menuFile->addAction(act2);

    // 创建中央控件
    edit = new QTextEdit(this);
    this->setCentralWidget(edit);
    edit->setPlaceholderText("此处编辑输入内容......");

    // 关联槽函数
    connect(act1, &QAction::triggered, this, &MainWindow::save);
    connect(act2, &QAction::triggered, this, &MainWindow::load);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::save()
{
    // 弹出对话框，显示写入文件的路径
    QFileDialog* dialog = new QFileDialog(this);
    QString filename = dialog->getSaveFileName(this, "保存文件", "D:/qt_code/2024_11/QMainWindow_3/", "*.txt");
    qDebug() << "filename: " << filename;

    // 写入文件
    std::ofstream file(filename.toStdString().c_str());
    if(!file.is_open())
    {
        qDebug() << "文件打开失败!";
        return;
    }

    const QString& text = edit->toPlainText();
    file << text.toStdString();
    file.close();
}

void MainWindow::load()
{
    // 弹出对话框，显示读取文件的路径
    QFileDialog* dialog = new QFileDialog(this);
    QString filename = dialog->getOpenFileName(this, "读取文件", "D:/qt_code/2024_11/QMainWindow_3/");
    qDebug() << "filename: " << filename;

    // 读取文件
    std::ifstream file(filename.toStdString().c_str());
    if(!file.is_open())
    {
        qDebug() << "文件打开失败!";
        return;
    }

    std::string content;
    std::string line;
    while(std::getline(file, line))
    {
        content += line;
        content += '\n';
    }
    file.close();

    // 显示到对话框
    QString text = QString::fromStdString(content);
    edit->setPlainText(text);
}
